package com.example.demo.interceptor;

import com.example.demo.annotation.SysLog;
import com.example.demo.bean.po.SysLogEntity;
import com.example.demo.service.SysLogService;
import com.example.demo.utils.HttpContextUtils;
import com.example.demo.utils.IpUtils;
import com.google.gson.Gson;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lyc on 2019/6/9.
 * 系统日志，切面处理类
 * 可以使用@Order注解指定切面的优先级，值越小优先级越高。
 */
@Aspect
@Component
public class SysLogHandler {

    @Autowired
    private SysLogService sysLogService;

    /**
     * 线程池 异步记录日志
     */
    private static ExecutorService logExecutorService =  Executors.newFixedThreadPool(10);

    @Pointcut("@annotation(com.example.demo.annotation.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //获取request  RequestContextHolder 是ThreadLocal 对象异步不是一个线程
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //注释下面可以直接响应出去 改变结果
        //HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //httpServletResponse.getWriter().print("ok");
        //return null;
        //保存日志 注意如果方法执行错误这不会记录日志
       logExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                saveSysLog(point, time,httpServletRequest);
            }
        });
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time,HttpServletRequest request) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLogEntity sysLog = new SysLogEntity();
        SysLog syslog = method.getAnnotation(SysLog.class);
        if(syslog != null){
            //注解上的描述
            sysLog.setOperation(syslog.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        try{
            String params = new Gson().toJson(args);
            sysLog.setParams(params);
        }catch (Exception e){

        }

        //获取request 这里获取直接 报错 debug 原因是 RequestContextHolder 是ThreadLocal 对象异步不是一个线程
       // HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IpUtils.getIpAddr(request));

        //用户名 根据实际登入获取
        String username = "";
        sysLog.setUsername(username);

        sysLog.setTime(time);
        sysLog.setCreateDate(new Date());
        //保存系统日志
        sysLogService.save(sysLog);
    }
}
